package com.jxb.test20241216;

import com.jxb.tree.TreeNode;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

public class BinTreeInOrderTraversal_94 {

    public static void main(String[] args) {

    }

    public List<Integer> inorderTraversal(TreeNode root) {
        //返回结果
        List<Integer> res = new ArrayList<>();
        accessTree(root,res);
        return res;
    }

    private void accessTree(TreeNode root, List<Integer> res) {
        if (root == null) {
            return;
        }
        accessTree(root.left,res);
        res.add(root.val);
        accessTree(root.right,res);
    }

    public List<Integer> inorderTraversalWithLoop(TreeNode root) {
        //返回结果
        List<Integer> res = new ArrayList<>();
        Deque<TreeNode> stack = new LinkedList<>();
        while (root != null || !stack.isEmpty()) {
            //将所有左节点入队
            while (root != null) {
                stack.push(root);
                root = root.left;
            }
            TreeNode treeNode = stack.pop();
            res.add(treeNode.val);
            root = root.right;
        }
        return res;
    }
}
